package com.gjw.blog.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.redisson.api.RedissonClient;
import org.redisson.spring.cache.CacheConfig;
import org.redisson.spring.cache.RedissonSpringCacheManager;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gjw19
 * @since 2019/11/7.
 * 为了让我们的存到redis中的缓存数据能更加容易看懂，
 * 这里换一种序列化方式，默认的是jdk的序列化方式，
 * 这里选用jackson2JsonRedisSerializer。
 * 只需要重写redisTemplate操作模板的生成方式即可。
 */
@EnableCaching
@Configuration
public class RedisConfiguration {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        jackson2JsonRedisSerializer.setObjectMapper(new ObjectMapper());

        template.setKeySerializer(jackson2JsonRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);

        return template;

    }

    /**
     * 配置缓存（必要）
     *
     * @param redissonClient
     * @return
     */
    @Bean
    CacheManager cacheManager(RedissonClient redissonClient) {
        Map<String, CacheConfig> config = new HashMap<>();
        // 创建一个名称为"cache_post"的缓存，过期时间ttl为30分钟，同时最长空闲时maxIdleTime为10分钟。
        config.put("cache_post", new CacheConfig(30 * 60 * 1000, 10 * 60 * 1000));
        return new RedissonSpringCacheManager(redissonClient, config);
    }
}
